import {onMounted} from 'vue'

type Options = {
  el: string
}
export default function (options: Options): Promise<string | null> {
  // @ts-ignore
  return new Promise((resolve, reject) => {
    const base64 = (img: HTMLImageElement) => {
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      canvas.width = img.width
      canvas.height = img.height
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
      return canvas.toDataURL('image/png')
    }

    onMounted(() => {
      let img: HTMLImageElement = document.querySelector(options.el) as HTMLImageElement
      img.onload = () => {
        resolve(base64(img))
      }
      img.onerror = () => {
        reject(null)
      }
    })
  })
}
